package com.boot.proofing.mpweb.base.service.impl;/**
 * @description
 * @autor xbwu on 2018/5/25.
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.core.service.impl.BaseMPServiceImpl;
import com.boot.proofing.common.util.EncryptUtils;
import com.boot.proofing.mpweb.base.entity.User;
import com.boot.proofing.mpweb.base.mapper.UserMapper;
import com.boot.proofing.mpweb.base.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User 表数据服务层接口实现类
 */
@Service("userServiceMP")
public class UserServiceImpl extends BaseMPServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public User findByUserAccount(String account) {
        List<User> list = baseMapper.selectList(Wrappers.<User>query().lambda().and(i->i.eq(User::getAccount, account)));
        return list != null && !list.isEmpty() ? list.get(0) : null;
    }

    @Override
    public IPage<User> selectLikeForPage(Page<User> page, String keyword) {
        QueryWrapper<User> cd= Wrappers.query();
        if(StringUtils.isNotBlank(keyword)){
            cd.lambda().and(
                    i->i.or().like(User::getAccount,keyword)
                            .or().like(User::getEmail,keyword)
                            .or().like(User::getUsername,keyword));
        }
        IPage<User> ipage = baseMapper.selectPage(page, cd);
        return ipage;
    }

    @Override
    public boolean saveOrUpdate(User entity) {
        if(entity.getId()!=null){
            //账号不允许更新
            entity.setAccount(null);
        }
        if(StringUtils.isNotBlank(entity.getPassword())){
            try {
                entity.setPassword(EncryptUtils.encryptPassword(entity.getPassword()));
            }catch(Exception e){
                logger.error(e.getMessage(),e);
                return false;
            }
        }
        return super.saveOrUpdate(entity);
    }


    @Override
    public boolean updatePasswordById(Long userId,String newPassword){
        User u=getById(userId);
        try {
            u.setPassword(EncryptUtils.encryptPassword(newPassword));
        }catch (Exception e){
            logger.error("加密密码错误，原因{}",e.getMessage());
            return false;
        }
        return updateById(u);
    }

    /**
     * 判断新旧头像是否相同
     *
     * @param userId
     * @param newHeadPath
     * @return
     */
    @Override
    public boolean headIsEquals(Long userId, String newHeadPath) {
        User user=getById(userId);
        if(newHeadPath.equals(user.getHeadPath())){
            return true;
        }else{
            return false;
        }
    }

}